package org.icedata.controller;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.icedata.dao.UnitRepository;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletContext;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Map;

@RestController
public class StaticController {
    private static final Logger logger = LogManager.getLogger(StaticController.class);

    @GetMapping("/static/{filename:.+}")
    @ResponseBody
    public ResponseEntity<Resource> serveStaticFile(@PathVariable String filename) {
        logger.info("访问\t静态资源" + filename);
        String[] allowedExtensions = {".html", ".css", ".js", ".png", ".jpg"};

        for (String extension : allowedExtensions) {
            if (filename.endsWith(extension)) {
                try {
                    // 使用UrlResource加载静态文件
                    UrlResource resource = new UrlResource("classpath:/static/" + filename);
                    if (resource.exists()) {
                        return ResponseEntity.ok()
                                .body(resource);
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
            }
        }
        logger.info("访问\t静态资源" + filename + "不存在 响应404");
        // 如果文件不符合要求，返回 404 - Not Found
        return ResponseEntity.notFound().build();
    }

    // 根据文件后缀获取 ContentType
    private String getContentTypeForExtension(String extension) {
        Map<String, String> contentTypeMapping = new HashMap<>();
        contentTypeMapping.put(".html", "text/html");
        contentTypeMapping.put(".css", "text/css");
        contentTypeMapping.put(".js", "application/javascript");
        contentTypeMapping.put(".png", "image/png");
        contentTypeMapping.put(".jpg", "image/jpeg");

        return contentTypeMapping.getOrDefault(extension, "application/octet-stream");
    }

}
